package org.example.utils

import org.example.common.Pattern
import org.example.constant.ApolloConst
import redis.clients.jedis.{Jedis, JedisPool, JedisPoolConfig}


class RedisSink(makeJedisPool : () => JedisPool) extends Pattern with Serializable {

  lazy val pool: JedisPool = makeJedisPool()

  def usingRedis[A](execute:Jedis=>A):A = using(pool.getResource)(execute)
}

/**
 * redis储存类
 */
object RedisSink {

  def apply(): RedisSink = {
    val createJedisPoolFunc = () => {
      val config = new JedisPoolConfig
      val pool = new JedisPool(config,ApolloConst.redisHost,ApolloConst.redisPort,1000*2,ApolloConst.redisPassword)
      val hook = new Thread{
        override def run(): Unit = {pool.destroy()}
      }
      sys.addShutdownHook(hook)
      pool
    }
    new RedisSink(createJedisPoolFunc)
  }

  def main(args: Array[String]): Unit = {
    val sink = RedisSink()
    sink.usingRedis{x=>
      x.select(9)
      println(x.hget("airport","22|aa"))
    }
  }
}
